#include <combaseapi.h>

#include <QApplication>
#include <QDir>

#include <osgDB/Registry>

#include "mainwindow.h"
#include "Log.h"
#include "Registry.h"
#include "AppCurrentEvent.h"
//#include "QtDeclareMetaTypes.h"
#include "TextureManager.h"
#include "GLSLPrograms.h"
#include "Ent.h"

void installTranslatorAndSetLang()
{
	Registry &reg = Registry::instance();
	reg.addTranslator("zh", "Miss_zh.qm", QCoreApplication::applicationDirPath());
	// TODO: check languange by system setting
	reg.setLanguage("zh");
}

void initTexture()
{
}

bool interceptQAcessible();
bool restoreQAcessible();

int main(int argc, char *argv[])
{
	CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
	QDir::setCurrent(QCoreApplication::applicationDirPath());
	//registerMetaTypes();
	QApplication app(argc, argv);
	RibbonStyle *ribbonStyle = new RibbonStyle;
	ribbonStyle->setTheme(OfficeStyle::Office2010Silver);
	app.setStyle(ribbonStyle);
	initOpenGLFormat();
	blog::initLog("CloudPictureViewer.log");
	// Must keep the order!!!
	// 1. create translators; 2. set language to cause changeEvent to be called. 3. show window;
	installTranslatorAndSetLang();
	initTexture();
	regAllEnts();
	osgDB::Registry::instance()->setDataFilePathList(QCoreApplication::applicationDirPath().toStdString());
	QCoreApplication::instance()->installEventFilter(&AppCurrentEvent::instance());
	// 有些机器上点击树控件程序会失去响应，在Qt内部进入死循环。拦截掉QAccessible会解决这个错误。
	bool intercepted = interceptQAcessible();
	MainWindow mainWin;
	mainWin.showMaximized();

	// 检查是否有文件参数传入
	if (app.arguments().count() > 1)
	{
		QString filePath = app.arguments().at(1);

		// 验证文件是否存在
		if (filePath.endsWith(".mdjson") && QFileInfo::exists(filePath))
		{
			mainWin.openRecentFile(filePath);
		}
	}

	int ret = app.exec();
	QCoreApplication::instance()->removeEventFilter(&AppCurrentEvent::instance());
	if (intercepted)
	{
		restoreQAcessible();
	}
	blog::flushAndTermLog();
	::CoUninitialize();
	return ret;
}
